package dcc.component;

import java.util.List;

import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import org.jdesktop.beansbinding.BeanProperty;
import org.jdesktop.swingbinding.JListBinding;
import org.jdesktop.swingbinding.SwingBindings;

import dcc.mbg.model.Dictionary;
import dcc.mbg.model.DictionaryItem;
import dcc.tools.BeanFactory;

public class JDictionaryList extends JList {

	private JDictionaryItemTable itemTable;
	private JDictionaryPanel dictionaryPanel;

	public JDictionaryList(JDictionaryPanel dictionaryPanel,
			JDictionaryItemTable itemTable) {
		this.dictionaryPanel = dictionaryPanel;
		this.itemTable = itemTable;
		this.itemTable.setDictionaryList(this);
		addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				updateTable();
			}
		});
	}

	public void updateTable() {
		Dictionary dictionary = getDictionary("" + getSelectedValue());
		if (dictionary != null) {
//			List<DictionaryItem> values = ((DictionaryService) BeanFactory
//					.getBean("dictionaryService")).getAllValuesByKey(dictionary
//					.getId());
//			dictionary.setValues(values);
			itemTable.update(dictionary);
			dictionaryPanel.createNewItem(dictionary.getId());
		}
	}

	private Dictionary getDictionary(String key) {
		for (Dictionary dictionary : this.dictionarys) {
			if (dictionary.getKey().equals(key)) {
				return dictionary;
			}
		}
		return null;
	}

	public void update() {
//		dictionarys = ((DictionaryService) BeanFactory
//				.getBean("dictionaryService")).getAllKey();
//		initDataBindings(dictionarys);
		this.setSelectedIndex(0);
	}

	private List<Dictionary> dictionarys;

	private void initDataBindings(List<Dictionary> dictionarys) {
		JListBinding<Dictionary, List<Dictionary>, JList> jListBinding = SwingBindings
				.createJListBinding(UpdateStrategy.READ, dictionarys, this,
						"Key");
		//
		BeanProperty<Dictionary, String> dictionaryBeanProperty = BeanProperty
				.create("key");
		jListBinding.setDetailBinding(dictionaryBeanProperty);
		//
		jListBinding.bind();
	}
}
